var express = require('express');
var router = express.Router();
const { Article } = require('../models');
const { failureResponse, successResponse } = require('../utils/responses');
const { NotFoundError } = require('../utils/errors')
const { setKey, getKey } = require('../utils/redis');

router.get('/', async function(req, res, next) {
  try {
    const currentPage = parseInt(req.query.currentPage) || 1;
    const pageSize = parseInt(req.query.pageSize) || 10;
    const offset = (currentPage - 1) * pageSize;

    const cacheKey = `articles:${currentPage}:${pageSize}`;
    let data = await getKey(cacheKey)
    if (data) {
      successResponse(res, '查询文章列表成功',data)
      return
    }


    const condition = {
      attributes: { exclude: ['content'] },
      order: [['id', 'DESC']],
      limit: pageSize,
      offset: offset
    }
    const { rows, count } = await Article.findAndCountAll(condition)
    data = {
      articles: rows,
      pagination: {
        pageSize,
        currentPage,
        total: count
      }
    }
    await setKey(cacheKey, data)
    successResponse(res, '查询文章列表成功', {
      articles: rows,
      pagination: {
        pageSize,
        currentPage,
        total: count
      }
    })
  } catch (error) {
    failureResponse(res, error);
  }
});

router.get('/:id', async function(req, res, next) {
  try {
    const article = await Article.findByPk(req.params.id);
    if (!article) {
      throw new NotFoundError('详情文章没有找到')
    }
    successResponse(res, '查询文章详情成功', { article })
  } catch (error) {
    failureResponse(res, error);
  }
});

module.exports = router;